package com.huishi.ui.component;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.huishi.entity.DataXTaskInfo;
import com.huishi.mapper.DataXTaskInfoMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import javax.annotation.PostConstruct;
import javax.swing.*;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.text.SimpleDateFormat;
import java.util.List;


//@org.springframework.stereotype.Component
@Slf4j
public class DataTaskRecordUI extends JFrame {

    @Autowired
    private DataXTaskInfoMapper dataXTaskInfoMapper;
    @Autowired
    @Qualifier("threadPoolTaskExecutor")
    private ThreadPoolTaskExecutor executor;

    private int currentPage = 1;  // 当前页码
    private int rowsPerPage = 10;  // 默认每页显示的行数
    private int totalPage;  // 总页数
    private List<DataXTaskInfo> data;  // 原始数据
    private DefaultTableModel model;
    private JLabel pageLabel;
    private JComboBox<Integer> rowsPerPageComboBox;

    @PostConstruct
    public void init() {
        executor.execute(this::initData);
    }

    private void initData() {
        // 初始化数据
        data = getDataFromDB();
        // 计算总页数
        totalPage = (int) Math.ceil((double) data.size() / rowsPerPage);

        // 表头
        String[] columnNames = {
                "ID", "任务名称", "表名", "时间戳字段", "写入模式",
                "首次执行时间", "执行间隔", "执行间隔单位",
                "最后执行时间", "状态", "任务类型", "创建时间", "更新时间"
        };

        // 创建表格模型，加载第一页数据
        model = new DefaultTableModel(getPageData(currentPage), columnNames) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false; // 禁止修改数据
            }
        };

        JTable table = new JTable(model);
        table.setFillsViewportHeight(true);
        table.setRowHeight(25);

        // 设置表头居中显示
        DefaultTableCellRenderer headerRenderer = new DefaultTableCellRenderer();
        headerRenderer.setHorizontalAlignment(JLabel.CENTER);
        table.getTableHeader().setDefaultRenderer(headerRenderer);

        // 设置单元格内容居中显示并加上鼠标悬停提示
        DefaultTableCellRenderer cellRenderer = new DefaultTableCellRenderer() {
            @Override
            public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
                JLabel label = (JLabel) super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
                label.setHorizontalAlignment(JLabel.CENTER);
                label.setToolTipText(value == null ? "" : value.toString()); // 鼠标悬停提示完整内容

                return label;
            }
        };
        table.setDefaultRenderer(Object.class, cellRenderer);

        // 添加表格到滚动面板
        JScrollPane scrollPane = new JScrollPane(table);
        add(scrollPane, BorderLayout.CENTER);

        // 创建分页控件
        JPanel paginationPanel = new JPanel();

        // 创建“每页行数”选择框
        rowsPerPageComboBox = new JComboBox<>(new Integer[]{5, 10, 15, 20});
        rowsPerPageComboBox.setSelectedItem(rowsPerPage);
        rowsPerPageComboBox.addActionListener(e -> {
            rowsPerPage = (Integer) rowsPerPageComboBox.getSelectedItem();
            totalPage = (int) Math.ceil((double) data.size() / rowsPerPage);
            currentPage = 1;
            updateTableData();
            pageLabel.setText("当前页: " + currentPage + " / " + totalPage);
        });

        // 创建翻页按钮和页码标签
        pageLabel = new JLabel("当前页: " + currentPage + " / " + totalPage);
        JButton prevButton = new JButton("上一页");
        JButton nextButton = new JButton("下一页");

        paginationPanel.add(new JLabel("每页显示: "));
        paginationPanel.add(rowsPerPageComboBox);
        paginationPanel.add(prevButton);
        paginationPanel.add(pageLabel);
        paginationPanel.add(nextButton);
        add(paginationPanel, BorderLayout.SOUTH);

        // 添加上一页按钮的事件
        prevButton.addActionListener(e -> {
            if (currentPage > 1) {
                currentPage--;
                updateTableData();
                pageLabel.setText("当前页: " + currentPage + " / " + totalPage);
            }
        });

        // 添加下一页按钮的事件
        nextButton.addActionListener(e -> {
            if (currentPage < totalPage) {
                currentPage++;
                updateTableData();
                pageLabel.setText("当前页: " + currentPage + " / " + totalPage);
            }
        });
    }

    public DataTaskRecordUI() {

        // 创建窗口
        setTitle("同步任务记录");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(1000, 500);

        // 设置窗口可见
        setVisible(false);
    }

    // 获取当前页的数据
    private Object[][] getPageData(int page) {
        int start = (page - 1) * rowsPerPage;
        int end = Math.min(start + rowsPerPage, data.size());
        Object[][] pageData = new Object[end - start][13];
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        for (int i = start; i < end; i++) {
            DataXTaskInfo task = data.get(i);
            pageData[i - start] = new Object[]{
                    task.getId(),
                    task.getTaskName(),
                    task.getTableName(),
                    task.getTimestampColumn(),
                    task.getWritemode(),
                    task.getFirstExecuteTime() == null ? "" : sdf.format(task.getFirstExecuteTime()),
                    task.getExecuteInterval(),
                    task.getExecuteIntervalUnit(),
                    task.getLastExecuteTime() == null ? "" : sdf.format(task.getLastExecuteTime()),
                    task.getState() == 1 ? "已完成" : "执行中",
                    task.getTaskType() == 1 ? "全量" : "增量",
                    task.getCreateTime() == null ? "" : sdf.format(task.getCreateTime()),
                    task.getUpdateTime() == null ? "" : sdf.format(task.getUpdateTime())
            };
        }
        return pageData;
    }

    // 更新表格数据
    private void updateTableData() {
        model.setDataVector(getPageData(currentPage), new String[]{
                "ID", "任务名称", "表名", "时间戳字段", "写入模式", "首次执行时间", "执行间隔",
                "执行间隔单位", "最后执行时间", "状态", "任务类型", "创建时间", "更新时间"
        });
    }

    // 模拟从数据库获取数据
    private List<DataXTaskInfo> getDataFromDB() {
        // 创建分页对象，传入页码和每页大小
        Page<DataXTaskInfo> page = new Page<>(currentPage, rowsPerPage);

        // 条件查询，如果不需要条件可以直接用空的 QueryWrapper
        QueryWrapper<DataXTaskInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("create_time");  // 按照创建时间排序

        // 执行分页查询
        Page<DataXTaskInfo> resultPage = dataXTaskInfoMapper.selectPage(page, queryWrapper);

        return resultPage.getRecords();
    }
}
